/*
 * 
 * Libman
 * 
 * Daniel Kaufmann, Martin Lang, Simon Moosbrugger,
 * Stefan Mayer, Stephan Halbeisen
 * 
 */
package application.controller.server;

import java.util.ArrayList;
import java.util.List;

import middleware.datacontainer.searchclient.ExemplarContainer;
import middleware.datacontainer.searchmedium.MediumContainer;
import model.Exemplar;
import model.Loan;
import model.Medium;
import model.dao.DAOFactory;
import application.exceptions.ExemplarNotFoundException;
import application.exceptions.MediumNotFoundException;

/**
 * The Class UseCaseControllerMediumSearch.
 */
public class UseCaseControllerMediumSearch extends AbstractUseCaseController {
	public UseCaseControllerMediumSearch() {
		super();
	}
	
	/**
	 * Search medium.
	 * 
	 * @param searchText
	 *            the search text
	 * @return the list
	 */
	public List<MediumContainer> searchMedium(String searchText) {
		String[] words = searchText.split(" ");

		List<Medium> mediums = DAOFactory.getInstance().getMediumDAO()
				.searchMedium(words, 50);

		ArrayList<MediumContainer> list = new ArrayList<MediumContainer>();

		for (Medium m : mediums) {
			list.add(new MediumContainer(m.getId(), m.getTitle(), m
					.getDescription(), m.getYear(), m.getLanguage()
					.getLanguage(), m.getDepartment().getDescription(), m
					.getClass().getName().replace("model.", "")));
		}

		return list;
	}

	/**
	 * Gets the exemplars.
	 * 
	 * @param mediumID
	 *            the medium id
	 * @return the exemplars
	 * @throws MediumNotFoundException
	 *             the medium not found exception
	 * @throws ExemplarNotFoundException
	 *             the exemplar not found exception
	 */
	public List<ExemplarContainer> getExemplars(Integer mediumID)
			throws MediumNotFoundException, ExemplarNotFoundException {
		List<ExemplarContainer> exemplars = new ArrayList<ExemplarContainer>();

		Medium medium = DAOFactory.getInstance().getMediumDAO()
				.findById(mediumID, false);

		if (medium == null) {
			throw new MediumNotFoundException();
		}

		for (Exemplar exemplar : medium.getExemplars()) {
			List<Loan> openLoans = DAOFactory.getInstance().getLoanDAO()
					.getOpenLoans(exemplar.getId(), 5);
			Boolean lend = openLoans.size() > 0 ? true : false;
			exemplars.add(new ExemplarContainer(exemplar.getId(), exemplar
					.getInvno(), lend));
		}

		return exemplars;
	}
}
